<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-08-25 09:54:45
 * @LastEditors: guandeshen 295570679@qq.com
 * @LastEditTime: 2024-09-02 11:27:58
 * @FilePath: /task-admin/src/views/wbs/components/AddTools/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by RSC, All Rights Reserved. 
-->
<template>
  <div class="content">
    <!-- 添加出售商品 -->
    <div
      class="border-l-[#4E6BEF] border-l-5px h-24px flex pl-8px text-[#323233] items-center text-16px font-900 mt-20px mb-16px"
    >
      {{ $t("common.addProductsForSale") }}
    </div>
    <div class="table-box">
      <el-table
        :data="newProductsData"
        :stripe="true"
        :header-cell-style="{
          'background-color': '#F6F7F9',
          color: '#8B8B99',
        }"
        style="width: 100%"
      >
        <el-table-column
          :label="$t('common.productName')"
          :show-overflow-tooltip="true"
          :min-width="140"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.asset_name }}</span>
            <el-select
              :placeholder="$t('common.pleaseSelect')"
              v-else
              v-model="scope.row.asset_id"
              @change="handleChange($event, scope.row, productsOption)"
            >
              <el-option
                v-for="option of productsOption"
                :key="option.id"
                :label="option.asset_name"
                :value="option.id"
              />
            </el-select>
            <!--  -->
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.supplier')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.supplier_name }}</span>
            <el-input
              v-else
              v-model="scope.row.supplier_name"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.unitPrice')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.unit_price }}</span>
            <el-input
              v-else
              v-model="scope.row.unit_price"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.quantity')" :min-width="120">
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.num }}</span>
            <el-input-number
              v-else
              style="width: 120px"
              v-model="scope.row.num"
              :min="1"
              :max="scope.row.stock"
              @change="handleNumChange($event, scope.row, 'sale')"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.totalPrice')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{
              Number(scope.row.unit_price) * scope.row.num
            }}</span>
            <el-input
              v-else
              v-model="scope.row.total_price"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.creator')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.createTime')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span>{{ scope.row.create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="viewType == 2"
          :label="$t('common.operation')"
          :min-width="80"
        >
          <template #default="{ $index, row }">
            <el-button
              type="danger"
              icon="delete"
              link
              @click="handleDeleteClick($index, newProductsData, row.id)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span
      v-if="viewType == 2"
      class="flex-center h-42px border-rd-8px bg-#F2F3F5 text-[#323233] font-900 text-14px cursor-pointer mt-16px hover:bg-#4E6BEF hover:text-[#fff]"
      @click="handleAddClick(newProductsData)"
      ><i-ep-plus class="close-icon mr-10px font-900" size="12px" />{{
        $t("common.addProducts")
      }}</span
    >
    <!-- 添加租赁工具 -->
    <div
      class="border-l-[#4E6BEF] border-l-5px h-24px flex pl-8px text-[#323233] items-center text-16px font-900 mt-30px mb-16px"
    >
      {{ $t("common.addRentalTools") }}
    </div>
    <div class="table-box">
      <el-table
        :data="newRentalData"
        :stripe="true"
        :header-cell-style="{
          'background-color': '#F6F7F9',
          color: '#8B8B99',
        }"
        style="width: 100%"
      >
        <el-table-column
          :label="$t('common.productName')"
          :show-overflow-tooltip="true"
          :min-width="140"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.asset_name }}</span>
            <el-select
              :placeholder="$t('common.pleaseSelect')"
              v-else
              v-model="scope.row.asset_id"
              @change="handleChange($event, scope.row, rentalOption)"
            >
              <el-option
                v-for="option of rentalOption"
                :key="option.id"
                :label="option.asset_name"
                :value="option.id"
              />
            </el-select>
            <!--  -->
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.supplier')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.supplier_name }}</span>
            <el-input
              v-else
              v-model="scope.row.supplier_name"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.rent')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.unit_price }}</span>
            <el-input
              v-else
              v-model="scope.row.unit_price"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.quantity')" :min-width="120">
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.num }}</span>
            <el-input-number
              v-else
              style="width: 120px"
              v-model="scope.row.num"
              :min="1"
              :max="scope.row.stock"
              @change="handleNumChange($event, scope.row, 'lease')"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.leaseDuration')" :min-width="120">
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.days }}</span>
            <el-input-number
              v-else
              style="width: 120px"
              v-model="scope.row.days"
              :min="1"
              :max="10000"
              @change="handleDaysChange($event, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.totalPrice')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{
              Number(scope.row.unit_price) * scope.row.num * scope.row.days
            }}</span>
            <el-input
              v-else
              v-model="scope.row.total_price"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.creator')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.createTime')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span>{{ scope.row.create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="viewType == 2"
          :label="$t('common.operation')"
          :min-width="80"
        >
          <template #default="{ $index, row }">
            <el-button
              type="danger"
              icon="delete"
              link
              @click="handleDeleteClick($index, newRentalData, row.id)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span
      v-if="viewType == 2"
      class="flex-center h-42px border-rd-8px bg-#F2F3F5 text-[#323233] font-900 text-14px cursor-pointer mt-16px hover:bg-#4E6BEF hover:text-[#fff]"
      @click="handleAddClick(newRentalData)"
      ><i-ep-plus class="close-icon mr-10px font-900" size="12px" />{{
        $t("common.addRental")
      }}</span
    >
  </div>
</template>

<script lang="ts" setup>
import { watchEffect } from "vue";
import type { IObject } from "@/hooks/usePage";
import { GoodsInfo } from "@/api/wbs/model";
import AssetssaleAPI from "@/api/assetssale";
import { AssetssaleList } from "@/api/assetssale/model";
import AssetsleaseAPI from "@/api/assetslease";
import { AssetsleaseList } from "@/api/assetslease/model";
import ProjectAPI from "@/api/project";

const { t } = useI18n();
const props = withDefaults(
  defineProps<{
    productsData: GoodsInfo[] | undefined;
    rentalData: GoodsInfo[] | undefined;
    viewType: number;
    wbsId: string;
  }>(),
  {
    productsData: () => {
      return [];
    },
    rentalData: () => {
      return [];
    },
    viewType: 2,
  }
);
const newProductsData = ref<GoodsInfo[]>([]);
const newRentalData = ref<GoodsInfo[]>([]);
watchEffect(() => {
  newProductsData.value = props.productsData;
  newRentalData.value = props.rentalData;
  // 这里可以执行更多响应式的副作用代码
});

// 点击删除
const handleDeleteClick = (index: number, list: GoodsInfo[], id?: string) => {
  if (id == "-1") {
    list.splice(index, 1);
  } else {
    ElMessageBox.confirm(t("common.confirmDeletion"), t("common.warning"), {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }).then(function () {
      ProjectAPI.deleteToolsByIds({
        wbs_id: props.wbsId,
        wbs_goods_id: id as string,
      }).then(() => {
        ElMessage.success(t("common.deleteSuccessful"));
        list.splice(index, 1);
      });
    });
  }
};

// const siteRef = ref<InstanceType<typeof PageContent>>();
const addRow = ref<GoodsInfo>({
  id: "-1",
  ref: "",
  asset_id: "",
  asset_type: "",
  asset_name: "",
  unit_price: "0",
  unit: "",
  num: 1,
  stock: 1,
  days: 1,
  total_price: 0,
  supplier_name: "",
});
const handleAddClick = (list: GoodsInfo[]) => {
  // 点添加的时候判断当前有没有新增的行，如果有判断是否全部已经填写，没有就提示，有就把ref给个随机值，然后增加一条数据
  if (list.some((item) => item.asset_id === "")) {
    ElMessage.error(t("common.pleaseFillFirst"));
    return;
  }
  if (list.length > 0) {
    list[list.length - 1].ref = Math.random().toString(36);
  }
  list.push(JSON.parse(JSON.stringify(addRow.value)));
};

const productsOption = ref<AssetssaleList[]>([]);
const rentalOption = ref<AssetsleaseList[]>([]);
const getProductsOption = () => {
  AssetssaleAPI.getPage({
    page: 1,
    page_size: 100000000,
  }).then((data) => {
    productsOption.value = data.list;
  });
};
const getRentalOption = async () => {
  AssetsleaseAPI.getPage({
    page: 1,
    page_size: 100000000,
  }).then((data) => {
    rentalOption.value = data.list;
  });
};
const initData = () => {
  getProductsOption();
  getRentalOption();
};

// 选择商品
const handleChange = (
  value: any,
  row: GoodsInfo,
  options: AssetssaleList[]
) => {
  const index = options.findIndex((option) => option.id === value);
  // 商品名称
  row.asset_name = options[index].asset_name;
  // 供应商
  row.supplier_name = options[index].supplier_name;
  // 单价
  row.unit_price = options[index].asset_unit_price;
  // 数量
  row.num = 1;
  // 租赁天数
  row.days = 1;
  // 库存
  row.stock = options[index].asset_qty;
  // 总价
  row.total_price = Number(row.unit_price) * row.days * row.num;
};
// 增加数量
const handleNumChange = (value: any, row: GoodsInfo, type: string) => {
  row.total_price =
    type == "lease"
      ? Number(row.unit_price) * Number(row.days) * value
      : Number(row.unit_price) * value;
};
// 租赁天数
const handleDaysChange = (value: any, row: GoodsInfo) => {
  row.total_price = Number(row.unit_price) * Number(row.num) * value;
};
onMounted(() => {
  initData();
});
defineExpose({ newProductsData, newRentalData });
</script>

<style scoped>
/* @import url(); 引入公共css类 */
:deep(.table-box) {
  margin-top: 0 !important;
  padding: 0 !important;
}
</style>
